package com.ftg.learn.sys.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ftg.learn.comm.entity.sys.User;
import com.ftg.learn.sys.user.service.IResourcesService;
import com.ftg.learn.sys.user.service.IUserService;
import com.ftg.learn.util.MD5;
import com.ftg.learn.util.ResBean;
import com.mysql.cj.util.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 登陆模块   包含登陆 功能以及登陆以后如何查看权限两个方法
 * @author kangjx
 * @date 2022/10/23
 */
@RestController
@Api(tags = "登陆模块")
@RequestMapping("/sys/login")
@SuppressWarnings("all")
public class LoginController {

    @GetMapping("/testnacoslb")
    public String testNacosLb(){
        return "大家好我是你要用到的exam-sys服务我的商品为8082";
    }

    @Resource
    IUserService iuser;

    @Resource
    IResourcesService iresources;

    private final String salt = "kjx_jwt";

    /**
     * 登陆功能
     */
    @ApiOperation("登陆功能")
    @PostMapping("/login")
    public ResBean checkUserInfo(
            @RequestParam(value = "username") @ApiParam(value = "帐号",defaultValue = "admin",required = true) String username,
            @RequestParam(value = "password") @ApiParam(value = "密码",defaultValue = "123456",required = true)String password
    ){

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_account",username);
        queryWrapper.eq("u_password",MD5.encrypt2ToMD5(password));
        User userInfo = iuser.getOne(queryWrapper);
        if(Objects.isNull(userInfo)){
            return ResBean.failNoPermission();
        }

        //jwt
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(userInfo.getId().toString())
                .setSubject(userInfo.getUaccount())
                .signWith(SignatureAlgorithm.HS256,salt);

        return ResBean.success(jwtBuilder.compact().toString());
    }


    /**
     * 根据登陆以后生成的jwt来查看登陆成功以后的用户权限
     * @param token 信息
     * @return ResBean
     */
    @GetMapping("/showResourceByUid")
    public ResBean showResourceByUid(
            @RequestHeader(value = "token")String token
    ){
        if(Objects.isNull(token)){
            return ResBean.failNoPermission();
        }

        Claims body = Jwts.parser()
                .setSigningKey(salt)
                .parseClaimsJws(token)
                .getBody();

        if(StringUtils.isNullOrEmpty(token)){
            return ResBean.failNoPermission();
        }
        String id = body.getId();
        Integer userId = Integer.valueOf(id);
        return ResBean.success(iresources.showResourceByUid(userId));
    }

}
